package com.jacobson.core.utils

import android.widget.FrameLayout
import android.app.Activity
import android.graphics.Rect
import android.view.View
import com.jacobson.core.base.Immersive


/**
 * ================================================
 *
 *  @author Wucz on 2018/8/9 9:47
 * ================================================
 */
class AndroidBug5497Workaround private constructor(activity: Activity, private val statusBar: Boolean = true) {

    private val mChildOfContent: View
    private var usableHeightPrevious: Int = 0
    private val frameLayoutParams: FrameLayout.LayoutParams
    private var immersive: Immersive? = null

    init {
        val content = activity.findViewById<View>(android.R.id.content) as FrameLayout
        mChildOfContent = content.getChildAt(0)
        mChildOfContent.viewTreeObserver.addOnGlobalLayoutListener { possiblyResizeChildOfContent() }
        frameLayoutParams = mChildOfContent.layoutParams as FrameLayout.LayoutParams
        activity.run {
            javaClass.getAnnotation(Immersive::class.java)?.let {
                immersive = it
            }
        }
    }

    private fun possiblyResizeChildOfContent() {
        val usableHeightNow = computeUsableHeight()
        if (usableHeightNow != usableHeightPrevious) {
            val usableHeightSansKeyboard = mChildOfContent.rootView.height
            val heightDifference = usableHeightSansKeyboard - usableHeightNow
            if (heightDifference > usableHeightSansKeyboard / 4) {
                // keyboard probably just became visible
                frameLayoutParams.height = usableHeightSansKeyboard - heightDifference
            } else {
                // keyboard probably just became hidden
                frameLayoutParams.height = usableHeightNow
            }
            mChildOfContent.requestLayout()
            usableHeightPrevious = usableHeightNow
        }
    }

    private fun computeUsableHeight(): Int {
        val r = Rect()
        mChildOfContent.getWindowVisibleDisplayFrame(r)
        return r.bottom - r.top + if (statusBar == true) {
            AppUtils.getStatusBarHeight(mChildOfContent.context)
        } else {
            0
        } /*- if (immersive?.fitNavigationBar == true) {
            AppUtils.getNavigationBarHeight(mChildOfContent.context).apply {
                LoggerFactory.getLogger("test").w("NavigationBarHeight = $this")
            }
        } else {
            0
        }*/
    }

    companion object {

        // For more information, see https://code.google.com/p/android/issues/detail?id=5497
        // To use this class, simply invoke assistActivity() on an Activity that already has its message view set.

        fun assistActivity(activity: Activity) {
            AndroidBug5497Workaround(activity)
        }
    }
}